package com.hw.nio.echo;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * 服务端
 */
public class EchoServer {

    /**
     * 实现思路：
     * 1、创建serverSocketChannel，绑定端口号，注册selector
     * 2、监听连接事件，监听到后增加读事件
     * 3、读事件读取数据，读完数据后返回一条数据
     */
    @Test
    public void echoSocketServer() throws IOException {
        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.bind(new InetSocketAddress(6666));
        channel.configureBlocking(false);
        Selector selector = Selector.open();
        channel.register(selector, SelectionKey.OP_ACCEPT);

        handle(selector, channel);


    }

    private void handle(Selector selector, ServerSocketChannel channel) throws IOException {

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int selectCount = selector.select();
            if (selectCount > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    if (selectionKey.isAcceptable()) {
                        SocketChannel socketChannel = channel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    } else if (selectionKey.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        if (socketChannel.isConnected()) {
                            buffer.clear();
                            socketChannel.read(buffer);
                            buffer.flip();
                            byte[] clientByte = new byte[buffer.remaining()];
                            buffer.get(clientByte);
                            System.out.println("client发出的消息：" + new String(clientByte, StandardCharsets.UTF_8));
                            long time = System.currentTimeMillis();
                            socketChannel.write(ByteBuffer.wrap(String.valueOf(time).getBytes()));
                        }


                    }
                }
            }
        }

    }
}
